package com.yenlien.traceyun.plant.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.business.dao.EquipmentDao;
import com.yenlien.traceyun.business.entity.Equipment;
import com.yenlien.traceyun.business.service.rest.usercenter.CompanyRestService;
import com.yenlien.traceyun.business.service.rest.usercenter.FileRestService;
import com.yenlien.traceyun.plant.dao.CompanyDao;
import com.yenlien.traceyun.plant.dao.SoilDao;
import com.yenlien.traceyun.plant.dao.SoilEquipmentDao;
import com.yenlien.traceyun.plant.dao.SoilFacilityDao;
import com.yenlien.traceyun.plant.entity.Company;
import com.yenlien.traceyun.plant.entity.Soil;
import com.yenlien.traceyun.plant.entity.SoilEquipment;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SoilService {
    @Autowired
    private SoilDao soilDao;
    @Autowired
    private SoilFacilityDao soilFacilityDao;
    @Autowired
    private FileRestService fileService;

    @Autowired
    private EquipmentDao equipmentDao;

    @Autowired
    CompanyDao companyDao;

    @Autowired
    private SoilEquipmentDao soilEquipmentDao;

    @Autowired
    private CompanyRestService companyRestService;

    public Page<Soil> findByList(final Soil soil) {
        Pageable pageable = PageRequest.of(soil.getPage(), soil.getPageSize(), Sort.Direction.DESC, ("createtime"));
        return soilDao.findAll(new Specification<Soil>() {
            private static final long serialVersionUID = -1396496630802017658L;

            @Override
            public Predicate toPredicate(Root<Soil> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Path<String> name = root.get("name");
                Path<String> peasantName = root.get("peasantName");
                Path<String> type = root.get("type");
                Path<String> isExist = root.get("isExist");
                //构造查询条件
                List<Predicate> list = new ArrayList<Predicate>();
                list.add(cb.equal(type, soil.getType()));
                list.add(cb.equal(isExist, soil.getIsExist()));
                Predicate[] predicateA = new Predicate[list.size()];
                Predicate predicateAnd = cb.and(list.toArray(predicateA));

                if (StringUtils.isNotEmpty(soil.getName())) {
                    List<Predicate> list2 = new ArrayList<>();
                    list2.add(cb.like(name, "%" + soil.getName() + "%"));
                    list2.add(cb.like(peasantName, "%" + soil.getPeasantName() + "%"));
                    Predicate[] predicateO = new Predicate[list2.size()];
                    Predicate predicateOr = cb.or(list2.toArray(predicateO));
                    return query.where(predicateAnd, predicateOr).getRestriction();
                } else {
                    return predicateAnd;
                }
            }
        }, pageable);
    }

    public Soil findById(String id) {
        return soilDao.findById(id);
    }

    public void save(Soil soil, List<MultipartFile> files) throws Exception {
        fileService.upload(null, soil, files);
        soilDao.save(soil);
    }

//	public void save(Soil soil, List<MultipartFile> files) throws Exception {
//		fileService.upload(null, soil, files);
//		soilDao.save(soil);
//	}

    public void deleteById(String id) {
        Soil soil = soilDao.findById(id);
        soil.setIsExist(1);
        soilDao.save(soil);
    }

    public void update(Soil soil, List<MultipartFile> files) throws Exception {
        fileService.upload(soilDao.findById(soil.getId()), soil, files);
        soilDao.save(soil);
    }

    public List<Soil> findAllBase() {
        return soilDao.findAllBase();
    }

    public List<Soil> findSoilByType(String type) {
        return soilDao.findSoilByType(type);
    }

    public void bind(JSONObject params) {
        List<SoilEquipment> list = new ArrayList<>();
        String soilId = params.getString("soilId");
        String type = params.getString("type");
        JSONArray equipmentIds = params.getJSONArray("equipments");
        for (int i = 0; i < equipmentIds.size(); i++) {
            SoilEquipment soilEquipment = new SoilEquipment();
            soilEquipment.setSoilId(soilId);
            soilEquipment.setType(type);
            JSONObject item = equipmentIds.getJSONObject(i);
            soilEquipment.setEquipmentId(item.getString("id"));
            soilEquipment.setCoordinate(item.getString("coordinate"));
            soilEquipment.setEquipmentName(item.getString("name"));
            list.add(soilEquipment);
        }
        soilFacilityDao.saveAll(list);
    }

    public List<Soil> findAll() {
        List<Soil> soils = soilDao.findAll();
        if (soils != null && soils.size() > 0) {
            for (Soil soil : soils) {
                //不是基地的话
                if (soil.getType() != 1) {
//					List<Equipment> equipmentList =equipmentDao.findById(soilEquipmentDao.findBySoilId(soil.getId()));
//					soil.setEquipments(equipmentList);
                    soil.setSoilEquipments(soilEquipmentDao.findBySoilId(soil.getId()));
                }

            }
        }
        return soils;
    }


    public List<Soil> findByBaseId(String baseId) {
        return soilDao.findByPidAndType(baseId, 2);
    }

    @Transactional
    public void updateEquipment(Equipment equipment) {
        equipmentDao.save(equipment);
        List<SoilEquipment> soilEquipments = soilEquipmentDao.findBySoilId(equipment.getId());
        if (soilEquipments != null && soilEquipments.size() > 0) {
            for (SoilEquipment soilEquipment : soilEquipments) {
                soilEquipment.setEquipmentName(equipment.getName());
                soilEquipment.setType(equipment.getType());
            }
            soilEquipmentDao.saveAll(soilEquipments);
        }
    }

    @Transactional
    public void deleteEquipment(String id) {
        equipmentDao.deleteById(id);
        soilEquipmentDao.deleteByEquipmentId(id);
    }

    public Object soils(String companyId) {
//        JSONObject jsonObject = (JSONObject) companyRestService.getchild(companyId);
//        JSONArray companies = jsonObject.getJSONArray("data");
        // 修正 数据中心 -> 生产监管 右边页面没数据的BUG
        List<String> collect = companyDao.getByPid(companyId).stream().map(Company::getId).collect(Collectors.toList());
        return soilDao.findByCompanyIdInAndType(collect, 2);
    }

    public Object soil(String companyId) {
        int i = 2;  //地块
        return soilDao.findByCompanyIdAndType(companyId, i).size();
    }

}
